import { Component, isValid, Toggle } from "cc";
import { noop } from "./ViewCompilerType";

export default function CompileCCLabel() {
    return {
        component: Toggle,
        binder: function(vm: any, attr: string, component: Component, hasSetter: boolean) {
            let unwatch = noop;
            let watchOptions = {
                sync: true,
                immediate: true,
            }
            if (!isValid(component)) {
                return unwatch;
            }
        
            let node = component.node;
        
            if (component instanceof Toggle) {
                // element->model 数据绑定
                node.on('toggle', (e: any) => {
                    if(hasSetter){
                        vm[attr] = component.isChecked;
                    }
                })
        
                // model->element 数据绑定
                unwatch = vm.$watch(attr, (value: any, oldValue: any) => {
                    if (!isValid(component)) {
                        unwatch?.();
                        return;
                    }
        
                    if (component.isChecked != value) {
                        component.setIsCheckedWithoutNotify(value);
                    }
                }, watchOptions)
            }
            return unwatch;
        }
    }
}